'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pay/kh/freePaySeries 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			series,
			series_id,
			pay_amount,
			tv_id,
			tv_name
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		// 支付金豆为 0 不执行扣除金豆的逻辑

		const user_bean = await db.collection('uni-id-users').doc(userInfo._id).get()
		if (user_bean.data[0].balance < pay_amount) {
			console.log("云函数余额不足");
			res.code = -1;
			res.money = -1;
			res.msg = "余额不足";
			res.tip = "余额不足";
			return res;
		}

		// 扣除用户金豆余额
		let newInfo = await vk.baseDao.updateAndReturn({
			dbName: "uni-id-users",
			whereJson: {
				_id: userInfo._id
			},
			dataJson: {
				balance: _.inc(-pay_amount)
			}
		});

		// 添加金豆收支明细
		res.add_jindou = await db.collection('a_jindou_detail').add({
			user_id: userInfo._id,
			nickname: userInfo.nickname || '匿名用户',
			change_num: pay_amount, //扣除的金豆数量
			changed_num: newInfo.balance, //支付后金豆余额
			change_reason: "购买" + tv_name + "第" + series + "集",
			type: "expend", //类型：expend:支出,income:收入。
			tfid: userInfo.tfid || "0", //投放链接的系统_ID
			middleman_id: userInfo.middleman_id || "0", //隶属机构
			invite_code: userInfo.invite_code || "0",
			ad_id: userInfo.ad_id || "0",
			os_name: originalParam.context.osName || "未知", //用户当时的系统
			appid: userInfo.appid || "0",
			appname: userInfo.appname || "0",
			_add_time: new Date().getTime()
		});

		res.add = await db.collection('a_had_pay').add({
			user_id: userInfo._id,
			nickname: userInfo.nickname || '匿名用户',
			series: series,
			pay_amount: pay_amount,
			series_id: series_id,
			tv_name: tv_name,
			tv_id: tv_id,
			middleman_id: userInfo.middleman_id || "0", //隶属机构
			tfid: userInfo.tfid || "0", //投放链接的系统_ID
			invite_code: userInfo.invite_code || "0",
			os_name: originalParam.context.osName || "未知", //用户当时的系统
			appid: userInfo.appid || "0",
			appname: userInfo.appname || "0",
			province: userInfo.province,
			city: userInfo.city,
			_add_time: new Date().getTime()
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}